<template>
  <el-form inline="true">
    <el-form-item label="创建日期">
      <el-date-picker
        v-model="datetimeRange"
        style="width: 240px"
        type="datetimerange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
      ></el-date-picker>
    </el-form-item>
    <el-form-item label="竞赛名称">
      <el-input
        v-model="params.title"
        placeholder="请您输入要搜索的竞赛名称"
        @keydown.enter="onSearch"
      />
    </el-form-item>
    <el-form-item>
      <el-button
        @click="onSearch"
        plain
      >搜索</el-button>
      <el-button
        @click="onReset"
        plain
        type="info"
      >重置</el-button>
      <el-button
        type="primary"
        :icon="Plus"
        plain
        @click="onAddExam"
      >添加竞赛</el-button>
    </el-form-item>
  </el-form>
  <!-- 表格 -->
  <el-table
    height="526px"
    :data="examList"
  >
    <el-table-column
      prop="title"
      label="竞赛标题"
    />
    <el-table-column
      prop="startTime"
      width="180px"
      label="竞赛开始时间"
    />
    <el-table-column
      prop="endTime"
      width="180px"
      label="竞赛结束时间"
    />
    <el-table-column
      label="是否开赛"
      width="100px"
    >
      <template #default="{ row }">
        <div v-if="!isNotStartExam(row)">
          <el-tag type="warning">已开赛</el-tag>
        </div>
        <div v-else>
          <el-tag type="info">未开赛</el-tag>
        </div>
      </template>
    </el-table-column>
    <el-table-column
      prop="status"
      width="100px"
      label="是否发布"
    >
      <template #default="{ row }">
        <div v-if="row.status == STATUS_TYPE.UN_PUBLISHED">
          <el-tag type="danger">未发布</el-tag>
        </div>
        <div v-if="row.status == STATUS_TYPE.PUBLISHED">
          <el-tag type="success">已发布</el-tag>
        </div>
      </template>
    </el-table-column>
    <el-table-column
      prop="createName"
      width="140px"
      label="创建用户"
    />
    <el-table-column
      prop="createTime"
      width="180px"
      label="创建时间"
    />
    <el-table-column
      label="操作"
      width="200px"
    >
      <template #default="{ row }">
        <el-button
          v-if="isNotStartExam(row) && row.status == STATUS_TYPE.UN_PUBLISHED"
          type="text"
          @click="onEdit(row.examId)"
        >编辑
        </el-button>
        <el-button
          v-if="isNotStartExam(row) && row.status == STATUS_TYPE.UN_PUBLISHED"
          type="text"
          @click="deleteExam(row)"
          class="red"
        >删除
        </el-button>
        <el-button
          v-if="row.status == STATUS_TYPE.PUBLISHED && isNotStartExam(row)"
          type="text"
          @click="cancelPublishExam(row)"
        >撤销发布</el-button>
        <el-button
          v-if="row.status == STATUS_TYPE.PUBLISHED && isNotStartExam(row)"
          type="text"
          @click="getExamDetail(row)"
        >查看详情</el-button>
        <el-button
          v-if="row.status == STATUS_TYPE.UN_PUBLISHED && isNotStartExam(row)"
          type="text"
          @click="publishExam(row)"
        >发布</el-button>
        <el-button
          type="text"
          v-if="!isNotStartExam(row)"
          @click="getExamDetail(row)"
        >已开赛 禁操作 可看详情</el-button>
      </template>
    </el-table-column>
  </el-table>
  <!-- 分页区域 -->
  <el-pagination
    background
    size="small"
    layout="total, sizes, prev, pager, next, jumper"
    :total="totalNum"
    v-model:current-page="params.pageNum"
    v-model:page-size="params.pageSize"
    :page-sizes="[5, 10, 15, 20]"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  />
</template>

<script setup>
  import { Plus } from '@element-plus/icons-vue'
  import { getExamListService, deleteExamByIdService, publishExamService, cancelPublishExamService } from '@/apis/exam';
  import { reactive, ref } from 'vue'
  import { PAGE_VALUE, OPERATION_TYPE } from '@/constants/CRUDConstants'
  import router from '@/router';
  import { STATUS_TYPE } from '@/constants/exam';
  function isNotStartExam(exam) {
    const now = new Date(); //当前时间
    return new Date(exam.startTime) > now || exam.status === STATUS_TYPE.UN_PUBLISHED
  }

  const params = reactive({
    pageNum: PAGE_VALUE.PAGE_NUM,
    pageSize: PAGE_VALUE.PAGE_SIZE,
    startTime: '',
    endTime: '',
    title: ''
  })

  const totalNum = ref(0) // 总个数
  const examList = ref([])
  const datetimeRange = ref([]) // 开始与结束时间列表

  async function getExamList() {
    if (datetimeRange.value.length > 0) {
      params.startTime = datetimeRange.value[0]
      params.endTime = datetimeRange.value[1]
    } else {
      params.startTime = ''
      params.endTime = ''
    }

    const { rows, total } = await getExamListService(params)
    examList.value = rows
    totalNum.value = total
  }
  getExamList()

  let oldSize = params.pageSize;
  function handleCurrentChange(newPage) {
    getExamList()
  }

  function handleSizeChange(newSize) {
    // 从客户角度出发 由多变少 那么就去当前页面的第一个值的页面 反之亦然
    const curFirstNum = (params.pageNum - 1) * oldSize + 1 // 当前页面的第一个值在总数中的位置
    params.pageNum = Math.ceil(curFirstNum / newSize)
    oldSize = newSize
    getExamList()
  }

  function onSearch() {
    params.pageNum = 1
    getExamList()
  }

  function onReset() {
    params.pageNum = PAGE_VALUE.PAGE_NUM
    params.pageSize = PAGE_VALUE.PAGE_SIZE
    params.startTime = ''
    params.endTime = ''
    params.title = ''
    datetimeRange.value.length = 0
    getExamList()
  }

  function onAddExam() {
    router.push(`/oj/layout/examUpdate?type=${OPERATION_TYPE.ADD}`)
  }

  function onEdit(examId) {
    router.push(`/oj/layout/examUpdate?examId=${examId}&type=${OPERATION_TYPE.EDIT}`)
  }

  async function getExamDetail(exam) {
    router.push(`/oj/layout/examUpdate?examId=${exam.examId}&type=${OPERATION_TYPE.DETAIL}`)
  }

  async function deleteExam(exam) {
    await ElMessageBox.confirm(`确定要删除[${exam.title}]竞赛吗？`, '提示', { type: 'warning', confirmButtonText: '确定', cancelButtonText: '取消' })
    await deleteExamByIdService(exam.examId)
    ElMessage.success('竞赛删除成功')
    params.pageNum = 1
    getExamList()
  }

  function updateExamStatus(exam) {
    exam.status = !exam.status
  }

  async function publishExam(exam) {
    try {
      await publishExamService(exam.examId)
      ElMessage.success('竞赛发布成功')
      updateExamStatus(exam)
    } catch (error) {
      getExamList()
    }
  }

  async function cancelPublishExam(exam) {
    try {
      await cancelPublishExamService(exam.examId)
      ElMessage.success('取消发布成功')
      updateExamStatus(exam) // 不通过请求来修改
    } catch (error) {
      getExamList()
    }
  }
</script>